package com.tnxst.phexamination.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.TimePickerView;
import com.luck.picture.lib.config.PictureConfig;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.constant.HISConfig;
import com.tnxst.phexamination.databinding.DoorRecordPhysicalDetermineBinding;
import com.tnxst.phexamination.dto.TCMHealthDTO;
import com.tnxst.phexamination.fragment.follow.DiabetesFollowFragment;
import com.tnxst.phexamination.public_health_docking_interface.DiabetesInterface;
import com.tnxst.phexamination.public_health_docking_interface.TCMHealthElderlyInterface;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.PictureFileUtil;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class PhysicalDetermineActivity extends BaseActivity {

    private GlobalViewModel viewModel;

    private DoorRecordPhysicalDetermineBinding binding;

    private TCMHealthDTO tcmHealthDTO;

    private Map<String, Integer> tcHealthGuides;

    private int position;

    private Map<String, Integer> scores;

    private Context context;

    //新增定位功能及拍照功能的控件
    private EditText address;

    private ImageView picture1;

    private ImageView picture2;

    private ImageView picture3;

    private Switch aSwitch;

    private Button start;

    private TextView del1;

    private TextView del2;

    private TextView del3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this)).get(GlobalViewModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.door_record_physical_determine);
        binding.setDoorRecordPhysicalDetermine(viewModel);
        binding.setLifecycleOwner(this);
        context = this;
        initData();
        initView();
        initAddress();
    }

    private void initAddress() {
        address = binding.include.findViewById(R.id.editTextTextPersonName33);
        picture1 = binding.include.findViewById(R.id.image1);
        picture2 = binding.include.findViewById(R.id.image2);
        picture3 = binding.include.findViewById(R.id.image3);
        aSwitch = binding.include.findViewById(R.id.isFinish);
        start = binding.include.findViewById(R.id.button22);
        del1 = binding.include.findViewById(R.id.text1);
        del2 = binding.include.findViewById(R.id.text2);
        del3 = binding.include.findViewById(R.id.text3);
        viewModel.getAddressUtils().getAddress(address, PhysicalDetermineActivity.this);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureFileUtil.showAlbum(PhysicalDetermineActivity.this, PictureConfig.CHOOSE_REQUEST);
            }
        });
        del1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tcmHealthDTO.setPicturePath1("");
                Utils.loadChatImage(PhysicalDetermineActivity.this,getResources().getDrawable(R.drawable.no_image), picture1);
            }
        });
        del2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tcmHealthDTO.setPicturePath2("");
                Utils.loadChatImage(PhysicalDetermineActivity.this,getResources().getDrawable(R.drawable.no_image), picture2);
            }
        });
        del3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tcmHealthDTO.setPicturePath3("");
                Utils.loadChatImage(PhysicalDetermineActivity.this,getResources().getDrawable(R.drawable.no_image), picture3);
            }
        });

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    tcmHealthDTO.setIsFinish(1);
                else
                    tcmHealthDTO.setIsFinish(0);
            }
        });

        if (StringUtils.isNotNull(tcmHealthDTO.getPicturePath1()))
            Utils.loadChatImage(PhysicalDetermineActivity.this,tcmHealthDTO.getPicturePath1(), picture1);
        if (StringUtils.isNotNull(tcmHealthDTO.getPicturePath2()))
            Utils.loadChatImage(PhysicalDetermineActivity.this,tcmHealthDTO.getPicturePath2(), picture2);
        if (StringUtils.isNotNull(tcmHealthDTO.getPicturePath3()))
            Utils.loadChatImage(PhysicalDetermineActivity.this,tcmHealthDTO.getPicturePath3(), picture3);
        if (StringUtils.isNotNull(tcmHealthDTO.getAddress())){
            address.setText(tcmHealthDTO.getAddress());
        } else{
            viewModel.getAddressUtils().getAddress(address, PhysicalDetermineActivity.this);
        }

        if (tcmHealthDTO.getIsFinish() == 0)
            aSwitch.setChecked(false);
        else
            aSwitch.setChecked(true);

    }

    private void initView() {
        if (StringUtils.isNotNull(tcmHealthDTO.getDoctorName())){
            binding.editText37.setText(tcmHealthDTO.getDoctorName());
            binding.editText37.setEnabled(false);
        }

        if (StringUtils.isNotNull(tcmHealthDTO.getFollowUpDate()))
            binding.textView198.setText(tcmHealthDTO.getFollowUpDate());

        if (StringUtils.isNotNull(tcmHealthDTO.getNextFollowUpDate()))
            binding.textView197.setText(tcmHealthDTO.getNextFollowUpDate());

        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Qi"))){
            Integer identity_qi = Integer.valueOf(tcHealthGuides.get("identity_Qi"));
            if (identity_qi != 0){
                List<Integer> list = Utils.divisionBinary(identity_qi);
                for (Integer integer : list) {
                    switch (integer){
                        case 1:
                            binding.radioButton65142.setChecked(true);
                            break;
                        case 2:
                            binding.radioButton63112.setChecked(true);
                            break;
                        case 3:
                            binding.radioButton6514.setChecked(true);
                            break;
                        case 4:
                            binding.radioButton6311.setChecked(true);
                            break;
                        case 5:
                            binding.radioButton65141.setChecked(true);
                            break;
                    }
                }
            }

        }
        binding.btnLefts2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });

        binding.btnLefts3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
                submit();
                tcmHealthDTO.setAddress(address.getText().toString());
                if (StringUtils.isNull(tcmHealthDTO.getAddress())
                        || (StringUtils.isNull(tcmHealthDTO.getPicturePath1())
                        && StringUtils.isNull(tcmHealthDTO.getPicturePath2())
                        && StringUtils.isNull(tcmHealthDTO.getPicturePath3()))){
                    Utils.Toast(context,"请完善地址信息或者拍摄现场图片后再保存！");
                    return;
                }
                viewModel.getTCMHealthRepository().insert(tcmHealthDTO);
                Utils.Toast(context,"保存本地成功！");
                finish();
            }
        });

        if (StringUtils.isNotNull(tcmHealthDTO.getTcHealthGuideOther()))
            binding.info.setText(tcmHealthDTO.getTcHealthGuideOther());

        binding.textView219.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String selected = binding.spinner6.getSelectedItem().toString();
                switch (selected){
                    case "平和质":
                        binding.info.setText(getResources().getString(R.string.Peaceful));
                        break;
                    case "阳虚质":
                        binding.info.setText(getResources().getString(R.string.Yang));
                        break;
                    case "痰湿质":
                        binding.info.setText(getResources().getString(R.string.Phlegm));
                        break;
                    case "阴虚质":
                        binding.info.setText(getResources().getString(R.string.Yin));
                        break;
                    case "湿热质":
                        binding.info.setText(getResources().getString(R.string.Hot));
                        break;
                    case "气郁质":
                        binding.info.setText(getResources().getString(R.string.StQi));
                        break;
                    case "特禀质":
                        binding.info.setText(getResources().getString(R.string.Specific));
                        break;
                    case "气虚质":
                        binding.info.setText(getResources().getString(R.string.Qi));
                        break;
                    case "血瘀质":
                        binding.info.setText(getResources().getString(R.string.Blood));
                        break;
                }
            }
        });
        if (StringUtils.isNull(binding.textView198.getText().toString()))
            binding.textView198.setText(Utils.getTime(new Date()));
        binding.textView198.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(PhysicalDetermineActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView198.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("随访时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });
        if (StringUtils.isNull(binding.textView197.getText().toString()))
            binding.textView197.setText(Utils.getTime(new Date()));
        binding.textView197.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(PhysicalDetermineActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView197.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("下次随访时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });
        if (StringUtils.isNotNull(tcmHealthDTO.getTcHealthHighScore())){
            switch (tcmHealthDTO.getTcHealthHighScore()){
                case "Peaceful":
                    binding.textView220.setText("平和质");
                    break;
                case "Yang":
                    binding.textView220.setText("阳虚质");
                    break;
                case "Phlegm":
                    binding.textView220.setText("痰湿质");
                    break;
                case "Qi":
                    binding.textView220.setText("气虚质");
                    break;
                case "Yin":
                    binding.textView220.setText("阴虚质");
                    break;
                case "Hot":
                    binding.textView220.setText("湿热质");
                    break;
                case "Blood":
                    binding.textView220.setText("血瘀质");
                    break;
                case "StQi":
                    binding.textView220.setText("气郁质");
                    break;
                case "Specific":
                    binding.textView220.setText("特禀质");
                    break;
            }
        }


        binding.spinner4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int p, long id) {
                save();
                binding.radioButton65142.setChecked(false);
                binding.radioButton63112.setChecked(false);
                binding.radioButton6514.setChecked(false);
                binding.radioButton6311.setChecked(false);
                binding.radioButton65141.setChecked(false);
                position = p;
                int identity = -1;
                int j = -1;
                switch (position){
                    case 0:
                        if (StringUtils.isNotNull(scores.get("Qi")))
                            binding.textView208.setText(String.valueOf(scores.get("Qi")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Qi"))){
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Qi"));
                        }
                        j = Integer.valueOf(tcmHealthDTO.getQualityDeficiency());
                        break;
                    case 1:
                        if (StringUtils.isNotNull(scores.get("Yang")))
                            binding.textView208.setText(String.valueOf(scores.get("Yang")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Yang")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Yang"));
                        j = Integer.valueOf(tcmHealthDTO.getYangQuality());
                        break;
                    case 2:
                        if (StringUtils.isNotNull(scores.get("Yin")))
                            binding.textView208.setText(String.valueOf(scores.get("Yin")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Yin")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Yin"));
                        j = Integer.valueOf(tcmHealthDTO.getYinQuality());
                        break;
                    case 3:
                        if (StringUtils.isNotNull(scores.get("Phlegm")))
                            binding.textView208.setText(String.valueOf(scores.get("Phlegm")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Phlegm")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Phlegm"));
                        j = Integer.valueOf(tcmHealthDTO.getPhlegm());
                        break;
                    case 4:
                        if (StringUtils.isNotNull(scores.get("Hot")))
                            binding.textView208.setText(String.valueOf(scores.get("Hot")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Hot")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Hot"));
                        j = Integer.valueOf(tcmHealthDTO.getDampHeat());
                        break;
                    case 5:
                        if (StringUtils.isNotNull(scores.get("Blood")))
                            binding.textView208.setText(String.valueOf(scores.get("Blood")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Blood")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Blood"));
                        j = Integer.valueOf(tcmHealthDTO.getBloodQuality());
                        break;
                    case 6:
                        if (StringUtils.isNotNull(scores.get("StQi")))
                            binding.textView208.setText(String.valueOf(scores.get("StQi")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_StQi")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_StQi"));
                        j = Integer.valueOf(tcmHealthDTO.getQiQuality());
                        break;
                    case 7:
                        if (StringUtils.isNotNull(scores.get("Specific")))
                            binding.textView208.setText(String.valueOf(scores.get("Specific")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Specific")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Specific"));
                        j = Integer.valueOf(tcmHealthDTO.getTeBingQuality());
                        break;
                    case 8:
                        if (StringUtils.isNotNull(scores.get("Peaceful")))
                            binding.textView208.setText(String.valueOf(scores.get("Peaceful")));
                        if (StringUtils.isNotNull(tcHealthGuides.get("identity_Peaceful")))
                            identity = Integer.valueOf(tcHealthGuides.get("identity_Peaceful"));
                        j = Integer.valueOf(tcmHealthDTO.getModerateQuality());
                        break;
                }
                if (identity != -1){
                    List<Integer> list = Utils.divisionBinary(identity);
                    for (Integer integer : list) {

                        switch (integer){
                            case 1:
                                binding.radioButton65142.setChecked(true);
                                break;
                            case 2:
                                binding.radioButton63112.setChecked(true);
                                break;
                            case 3:
                                binding.radioButton6514.setChecked(true);
                                break;
                            case 4:
                                binding.radioButton6311.setChecked(true);
                                break;
                            case 5:
                                binding.radioButton65141.setChecked(true);
                                break;
                        }
                    }
                }
                if (j != -1){
                    switch (j){
                        case 0:
                            binding.textView213.setText("否");
                            break;
                        case 1:
                            binding.textView213.setText("是");
                            break;
                        case 2:
                            binding.textView213.setText("倾向是");
                            break;
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void save(){
        int a = 0;
        if (binding.radioButton65142.isChecked())
            a += 1;
        if (binding.radioButton63112.isChecked())
            a += 2;
        if (binding.radioButton6514.isChecked())
            a += 4;
        if (binding.radioButton6311.isChecked())
            a += 8;
        if (binding.radioButton65141.isChecked())
            a += 16;

        int i = a;

        switch (position){
            case 0:
                tcHealthGuides.put("identity_Qi",i);
                break;
            case 1:
                tcHealthGuides.put("identity_Yang",i);
                break;
            case 2:
                tcHealthGuides.put("identity_Yin",i);
                break;
            case 3:
                tcHealthGuides.put("identity_Phlegm",i);
                break;
            case 4:
                tcHealthGuides.put("identity_Hot",i);
                break;
            case 5:
                tcHealthGuides.put("identity_Blood",i);
                break;
            case 6:
                tcHealthGuides.put("identity_StQi",i);
                break;
            case 7:
                tcHealthGuides.put("identity_Specific",i);
                break;
            case 8:
                tcHealthGuides.put("identity_Peaceful",i);
                break;
        }
    }

    private void submit(){
        tcmHealthDTO.setFollowUpDate(binding.textView198.getText().toString());
        tcmHealthDTO.setNextFollowUpDate(binding.textView197.getText().toString());
        if (StringUtils.isNotNull(binding.editText37.getText().toString()))
            tcmHealthDTO.setDoctorName(viewModel.getUserInfo().getDoctorName());
        tcmHealthDTO.setTcHealthGuides(GsonUtils.toJson(tcHealthGuides));
        if (StringUtils.isNotNull(binding.info.getText().toString()))
            tcmHealthDTO.setTcHealthGuideOther(binding.info.getText().toString());
        tcmHealthDTO.setDoctorID(viewModel.getUserInfo().getDId());
        }


    private void initData() {
        tcmHealthDTO = (TCMHealthDTO) getIntent().getSerializableExtra("tcmHealthDTO");
        if (StringUtils.isNotNull(tcmHealthDTO.getTcHealthGuides()))
            tcHealthGuides = GsonUtils.toMap(tcmHealthDTO.getTcHealthGuides(),String.class,Integer.class);
        else
            tcHealthGuides = new LinkedHashMap<>();
        scores = GsonUtils.fromJson(getIntent().getStringExtra("scores"),Map.class);
    }

}